package com.shaozi.nc.manage;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.shaozi.common.schedule.DyncQuartzManage;
import com.shaozi.lib.manage.ManageBase;
import com.shaozi.lib.throwable.SzException;
import com.shaozi.nc.data.model.CompanyInfoModel;
import com.shaozi.nc.data.model.PushMsgModel;
import com.shaozi.nc.data.model.SubPushMsgModel;
import com.shaozi.nc.data.mongodao.PushMsgMDao;
import com.shaozi.nc.quartz.job.PushMsgJob;
import com.shaozi.utils.common.BeanUtils;

/**
 * BeanUtils.getBean("pushMsgMgr");
 * 
 * @author brenx
 * 
 */
public class PushMsgManage extends ManageBase {

	private final Logger logger = Logger.getLogger(PushMsgManage.class);
	@Autowired
	private PushMsgMDao pushDao;

	public PushMsgManage() {

	}

	public void updateCompany(CompanyInfoModel compModel) {
		
		List<PushMsgModel> models = pushDao.getByCompId(compModel.getCompanyId());
		for (PushMsgModel model : models) {
			if (model != null) {
				schedulePush(compModel.getCompanyId(), model);
				return;
			}
		}
	}

	public List<PushMsgModel> getRunnableJob(String compId, int limit) {
		
		pushDao.removeExpired(compId);
		List<PushMsgModel> models = pushDao.getRunnableJob(compId, limit);
		return models;
	}

	/**
	 * 清除已过期的，调度中会自动清除，不需要再清
	 * 
	 * @param compId
	 */
	public void removeExpired(String compId) {
		
		pushDao.removeExpired(compId);
	}

	public PushMsgModel getMsgModel(String compId, String userId,String sourceId, int sourceType) {
		
		return pushDao.getBySource(compId, sourceType, userId, sourceId);
	}

	/**
	 * 按表nc_push_msg的_id，删除数据，并清除调度
	 * 
	 * @param compId
	 * @param sourceType
	 * @param _id
	 */
	public void remove(String compId, int sourceType, String _id) {
		
		pushDao.removePushMsg(compId, _id);
		String groupId = getGroupId(compId, sourceType);
		DyncQuartzManage quartzMgr = (DyncQuartzManage) BeanUtils.getBean("dyncQuartzMgr");
		try {
			quartzMgr.removeJob(groupId, _id, groupId, _id);
		} catch (SchedulerException e) {
			logger.error(SzException.getStackMessage(e));
		}
	}

	public List<PushMsgModel> addPushMsgNow(String compId, String userIds, String sourceId, int sourceType,
			Long expireTime, Integer repeatCount, Integer intervalTimeSec, boolean isBadge, String title,
			String content, Integer subPushIntervalSec, Integer subPushRepeatCount) {
		return addPushMsg(compId, userIds, sourceId, "-1", sourceType, expireTime, repeatCount, intervalTimeSec,
				isBadge, title, content, subPushIntervalSec, subPushRepeatCount);
	}

	/**
	 * @param compId
	 * @param userIds
	 *            用逗号分隔的id列表
	 * @param sourceId
	 * @param pushTimeRegex
	 *            -1:do it now
	 * @param sourceType
	 *            1: im, 2:oa
	 * @param expireTime
	 * @param repeatCount
	 * @param intervalTimeSec
	 * @param isBadge
	 * @param title
	 * @param content
	 * @param subPushIntervalSec
	 * @param subPushRepeatCount
	 */
	public List<PushMsgModel> addPushMsg(String compId, String userIds, String sourceId, String pushTimeRegex,
			int sourceType, Long expireTime, Integer repeatCount, Integer intervalTimeSec, boolean isBadge,
			String title, String content, Integer subPushIntervalSec, Integer subPushRepeatCount) {
		if (StringUtils.isEmpty(userIds)) {
			return null;
		}
		String[] userAry = userIds.split(",");
		Map<String, Integer> unique = new HashMap<String, Integer>();
		List<PushMsgModel> models = new ArrayList<PushMsgModel>(userAry.length);
	
		for (String userId : userAry) {
			PushMsgModel model = pushDao.getBySource(compId, sourceType, userId, sourceId);
			if (model == null) {
				model = new PushMsgModel();
			} else {
				if (unique.containsKey(model.getId())) {
					continue;
				}
			}
			if (subPushIntervalSec != null) {
				SubPushMsgModel subModel = new SubPushMsgModel();
				subModel.setCurRepeatCount(0);
				subModel.setIntervalSec(subPushIntervalSec);
				subModel.setRepeatCount(subPushRepeatCount == null ? 1 : subPushRepeatCount);
				subModel.setTotalRepeatCount(0);
				model.setSubModel(subModel);
			}
			model.setCompId(compId);
			model.setUserId(userId);
			model.setSourceId(sourceId);
			model.setPushTimeRegex(pushTimeRegex);
			model.setSourceType(sourceType);
			model.setDesignRepeatCount(repeatCount);
			model.setRepeatCount(0);
			model.setIsDel(0);
			model.setCreateTime(System.currentTimeMillis());
			model.setIsBadge(isBadge);
			model.setIntervalTime(intervalTimeSec);
			model.setLastPushTime(0l);
			model.setTitle(title);
			model.setContent(content);
			model.setExpireTime(expireTime == null ? 0 : expireTime);
			model.setNextPushTime(calcNextPushTime(model));
			pushDao.save(compId, model);
			if (StringUtils.isEmpty(model.getId())) {
				logger.warn("add push msg fail:" + model.toJsonStr());
				continue;
			}
			schedulePush(compId, model);
			unique.put(model.getId(), 1);
			models.add(model);
		}
		return models;
	}

	/**
	 * 下次执行时间，-1表示立即执行
	 * 
	 * @param model
	 * @return
	 */
	public long calcNextPushTime(PushMsgModel model) {
		try {
			if ("-1".equals(model.getPushTimeRegex())) {
				return -1l;
			} else {
				return DyncQuartzManage.getNextFireTime(model.getPushTimeRegex());
			}
		} catch (ParseException e) {
			logger.error(SzException.getStackMessage(e));
			return 0l;
		}
	}

	private void schedulePush(String compId, PushMsgModel model) {
		DyncQuartzManage quartzMgr = (DyncQuartzManage) BeanUtils.getBean("dyncQuartzMgr");
		try {
			String groupId = getGroupId(compId, model.getSourceType());
			quartzMgr.upsertJobTime(groupId, model.getId(), PushMsgJob.class, groupId, model.getId(),
					model.getPushTimeRegex());
		} catch (SchedulerException e) {
			logger.error(SzException.getStackMessage(e));
			if (!StringUtils.isEmpty(model.getId())) {
				if (e.getMessage().contains("never fire")) {
					remove(compId, model.getSourceType(), model.getId());
				}
			}
		}
	}

	private String getGroupId(String compId, int sourceType) {
		return String.format("%s_%d", compId, sourceType);
	}
}
